package com.cj.cms.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.cxf.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cj.cms.entity.Article;
import com.cj.cms.entity.Channel;
import com.cj.cms.entity.WebSite;
import com.cj.cms.service.ArticleManager;
import com.cj.cms.service.ChannelManager;
import com.cj.common.orm.Page;
import com.cj.common.orm.PropertyFilter;
import com.cj.common.orm.PropertyFilter.MatchType;
import com.cj.common.orm.hibernate.HibernateWebUtils;
import com.cj.common.web.struts2.Struts2Utils;

public class ChannelWebAction extends BaseWebAction{
	
	@Autowired
	private ChannelManager channelManager;
	@Autowired
	private ArticleManager articleManager;

	private Channel entity;
	
	private List<Channel> children;
	private String channelType;
	protected Page<Article> page = new Page<Article>(20,"isTop,modifyTime",Page.DESC + "," + Page.DESC);
	private WebSite webSite;
	private String viewFtl;
	public String execute(){
		try {
			if(StringUtils.isEmpty(channelType)){
				channelType = "home";
			}
			entity = channelManager.getByCode(channelType);
			children = channelManager.getChildren(entity.getId());
			webSite = entity.getWebSite();
			viewFtl = entity.getTemplate().getPath();
			HttpServletRequest request = Struts2Utils.getRequest();
			List<PropertyFilter> filters = HibernateWebUtils.buildPropertyFilters(request);
			if(entity != null)
				filters.add(new PropertyFilter("channel.id",entity.getId(),MatchType.EQ));
			if(entity.getArticleNum() != null)
				page.setPageSize(entity.getArticleNum());
			page = articleManager.search(page, filters);
			return SUCCESS;
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	public String webSiteMap(){
		try {
			entity = channelManager.getByCode("root");
			webSite = entity.getWebSite();
			children = channelManager.getChildren(entity.getId());
			return "websiteMap";
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}
	public String getChannelType() {
		return channelType;
	}

	public void setChannelType(String channelType) {
		this.channelType = channelType;
	}

	public String getViewFtl() {
		return viewFtl;
	}

	public Channel getEntity() {
		return entity;
	}

	public void setEntity(Channel entity) {
		this.entity = entity;
	}

	public WebSite getWebSite() {
		return webSite;
	}

	public void setWebSite(WebSite webSite) {
		this.webSite = webSite;
	}

	public Page<Article> getPage() {
		return page;
	}

	public void setPage(Page<Article> page) {
		this.page = page;
	}

	public List<Channel> getChildren() {
		return children;
	}
	
}
